package com.zhutengwei.android.zuji.activity;

import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/12/18.
 */
public class BaseActivity extends AppCompatActivity {

    interface GrantedListener{
        void onGranted();
        void onDenied(List<String> deniedPermissions);
    }

    public final int DENIED_REQUEST_CODE = 1;
    private GrantedListener mGrantedListener;

    public void getPermissions(String[] permissions, GrantedListener grantedListener){
        mGrantedListener = grantedListener;
        List<String> deniedPermission = new ArrayList<>();
        for (String permission : permissions) {
            if(ContextCompat.checkSelfPermission(this, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                //需要授权
                deniedPermission.add(permission);
            } else {
                //不需要授权
//                mGrantedListener.onGranted();
            }
        }
        if(!deniedPermission.isEmpty()){
            ActivityCompat.requestPermissions(this, deniedPermission.toArray(new String[]{}), DENIED_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        List<String> deniedPermission = new ArrayList<>();
        switch (requestCode) {
            case DENIED_REQUEST_CODE:
                for(int i = 0;i < permissions.length;i++){
                    String permission = permissions[i];
                    int grantResult = grantResults[i];
                    if(grantResult == PackageManager.PERMISSION_DENIED){
                        deniedPermission.add(permission);
                    }
                }
                break;
            default:
                break;
        }
        if(!deniedPermission.isEmpty()){
            mGrantedListener.onDenied(deniedPermission);
        } else {
            mGrantedListener.onGranted();
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
